package edu.whu.notepal.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import edu.whu.notepal.dto.UserDTO;
import edu.whu.notepal.utils.RedisConstants;
import edu.whu.notepal.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description 用于刷新token的拦截器 与前另一个拦截路径不同
 * @author 陈磊
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
        String token = request.getHeader("authorization");
        //token为空 拦截
        if(StrUtil.isEmpty(token)){
            return true;
        }
        //获取redis中的用户对象
        String tokenKey = RedisConstants.LOGIN_TOKEN_KEY + token;
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(tokenKey);
        if(entries.isEmpty()){
            return true;
        }
        //存储到ThreadLocal中 并刷新有效期
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        stringRedisTemplate.expire(tokenKey,RedisConstants.LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
